#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :test.py
# @Time      :2024/4/27
# @Author    :cl  coding
# @email     :

import json
from DrissionPage import ChromiumPage
# import time
# import os
from DrissionPage import ChromiumOptions
co = ChromiumOptions()
co.headless()  # 无头模式
def countdown(n):
    for i in range(n, 0, -1):
        print(f'\r倒计时{i}秒', end='')  # \r让光标回到行首 ，end=''--结束符为空，即不换行
        time.sleep(1)  # 让程序等待1秒
    else:
        print('\r倒计时结束')


def sign_in():
    sign_in_page = ChromiumPage()
    sign_in_page.get('https://www.douyin.com/?recommend=1')
    print('请扫码登录')
    countdown(30)


def delete_file(file_path):
    """用于删除初始化excel文件"""
    # 检查文件是否存在
    if os.path.exists(file_path):
        # 删除文件
        os.remove(file_path)
        print(f"已删除初始化excel文件：{file_path}")
    else:
        print(f"文件不存在：{file_path} ")



def get_page(url ='https://fluxlora.com/tools/prompt-generator',text =None):
    if text ==None:
        text = 'Realistic style, a laughing girl is looking at the puppy next to her'
    page = ChromiumPage(co)  # co
    page.refresh()
    page.clear_cache()
    #开始监听数据
    page.listen.start('https://fluxailab.com/tools/prompt-generator', method='POST')
    page.get(url,timeout=10)
    # print (page.html)
    prompts =[]
    try:
        # elea = page.ele('@tag()=textarea')  # 获取第一个textarea元素
        # elea = page.ele('.^f_')  # 获取第一个textarea元素
        elea = page.ele('xpath:/html/body/div/div/div[2]/textarea')  # 获取第一个textarea元素
        # print(str(elea.html))
        # 输入文本
        elea.input(text)
        # 点击按钮
        page.ele('xpath:/html/body/div/div/div[2]/button').click()
        # 等待页面加载完成
        res = page.listen.wait(timeout=10)  # 等待并获取一个数据包
        #解析数据
        data = res.response.body.split('\n1:')[1].strip()
        #转为json
        data = json.loads(data)
        #获取prompts
        prompts =data['data']['prompts']
        # print(prompts)

    except Exception as e:
        print(e)
    page.close()

    return prompts
def main():
    #重复调用,不停打开网页
    while True:
        text = input('请输入文本，停止请输如exit：')
        if text == 'exit':
            break
        prompts = get_page(text =text)
        print(prompts)

    # #重复调用,只打开一次网页，只需要在get_page中输入text内部循环即可

if __name__ == '__main__':
    print()
    # text = 'Mysterious eastern ink style with blue and white primary colors, a middle aged female looking at the back of a focused male.'
    # prompts = get_page(text = text)
    #
    # print(prompts)
    main()